'use strict';
const BaseService = require('./base');


class TaskService extends BaseService {

    async sleep(timer) {
        return new Promise(function (resolve, reject) {
            setTimeout(function () {
                resolve(timer);
            }, timer)
        })
    }

    async __getMaxUUIDAndCount(type) {
        let sql = 'select max(uuid) as maxUUID from sys_uid where type=? ';
        let result = await this.executeSqlFirst(sql, [type]);

        sql = 'select count(*) as count from sys_uid where type=? and valid=1 ';
        let resultCount = await this.executeSqlFirst(sql, [type]);

        let object = {
            maxUUID: Number(result.maxUUID) || 100000,
            maxCount: resultCount.count || 0
        };

        return object;
    }


    __checkUUIDValid($newUuid) {
        let newUuid = $newUuid.toString();

        let pp = [];

        let object = {};
        for (let i = 0; i < newUuid.length; i++) {
            pp.push(newUuid[i]);
            if (!object[newUuid[i]]) object[newUuid[i]] = [];
            object[newUuid[i]].push({num: newUuid[i], idx: i});
        }

        if (pp[pp.length - 1] == 4) {
            return 0;
        }

        let resp = {};

        for (let key in object) {

            let list = object[key];
            for (let i = 0; i < list.length; i++) {
                if (resp[list[i].num] === undefined) resp[list[i].num] = 1;
                if (list[i + 1] && list[i].idx + 1 === list[i + 1].idx) {
                    resp[list[i].num] = resp[list[i].num] += 1;
                } else {
                    if (i != list.length - 1)
                        resp[list[i].num] = 1;
                }
            }
        }

        let flag = 1;

        for (let key in resp) {
            if (resp[key] >= newUuid.length - 1 || (key == 4 && resp[key] >= 3)) {
                flag = 0;
            }
        }
        return flag;
    }


    async __getUUIDs() {

        let defaultList = [
            {type: 'U', defaultUUID: 100000, existCount: 0, generateCount: 10000, list: []},//用户
            {type: 'P', defaultUUID: 100000, existCount: 0, generateCount: 10000, list: []},//产品
        ];

        for (let i = 0; i < defaultList.length; i++) {
            let item = defaultList[i];

            let result = await this.__getMaxUUIDAndCount(item.type);

            item.defaultUUID = result.maxUUID;
            item.existCount = result.maxCount;
        }


        for (let i = 0; i < defaultList.length; i++) {
            let item = defaultList[i];

            let needCount = item.generateCount - item.existCount;

            if (needCount > 0) {//如果不够，则生成uuid
                let list = item.list;
                while (needCount - list.length > 0) {

                    let newUuid = item.defaultUUID + 1;

                    let valid = this.__checkUUIDValid(newUuid);
                    if (valid) {
                        item.defaultUUID = item.defaultUUID + 1;
                        list.push(newUuid);
                    } else {
                        item.defaultUUID = item.defaultUUID + 1;
                    }
                }
            }
        }
        return defaultList;
    }

    async genUUID() {
        console.log(`系统正在预生成uid`);
        let data = await this.__getUUIDs();

        for (let i = 0; i < data.length; i++) {
            let item = data[i];
            console.log(`正在生成 ${item.type} 量级：${item.list.length}`);
            let list = item.list;
            await Promise.all(list.map(async (uitem) => {
                let params = {
                    type: item.type,
                    uuid: uitem,
                    valid: 1
                };
                await this.executeInsert('sys_uid', params);
            }));
            console.log(`完成生成 ${item.type} 量级：${item.list.length}`);
        }
        console.log(`系统完成预生成uid`);
        return true;
    }


}

module.exports = TaskService;
